<route lang="yaml">
	meta:
	enabled: false
</route>

<script setup lang="ts">
	import { ref } from 'vue'
	import type { TabsPaneContext } from 'element-plus'
	import { ElLoading } from 'element-plus'
	import tinymce from 'tinymce/tinymce'
	import TinymceEditor from '@tinymce/tinymce-vue'
	import 'tinymce/themes/silver/theme'
	import 'tinymce/icons/default/icons'
	import 'tinymce/models/dom'
	import 'tinymce/plugins/autolink'
	import 'tinymce/plugins/autoresize'
	import 'tinymce/plugins/fullscreen'
	import 'tinymce/plugins/image'
	import 'tinymce/plugins/insertdatetime'
	import 'tinymce/plugins/link'
	import 'tinymce/plugins/lists'
	import 'tinymce/plugins/media'
	import 'tinymce/plugins/preview'
	import 'tinymce/plugins/table'
	import 'tinymce/plugins/wordcount'
	import 'tinymce/plugins/code'
	import 'tinymce/plugins/searchreplace'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import useSettingsStore from '@/store/modules/settings'
	import Api from '@/api/modules/setting/richtext'
	import setupApi from '@/api/zhitan/setup.ts'
	import userApi from '@/api/modules/users/user'
	import useUserStore from '@/store/modules/user'
	import { createDirectUploadTask, createMultipartUploadV2Task, FileData } from 'qiniu-js';

	const userStore : any = useUserStore()
	const loadicon = new URL('@/assets/images/loadicon.gif', import.meta.url).href
	const fullscreenLoading = ref(false)
	const baseurl : any = ref(`${import.meta.env.VITE_APP_API_BASEURLIMG}`)
	const settingsStore = useSettingsStore()
	const activeName = ref('1')
	const defaultSetting = ref({
		language_url: 'tinymce/langs/zh-Hans.js',
		language: 'zh-Hans',
		skin_url: settingsStore.settings.app.colorScheme === 'light' ? 'tinymce/skins/ui/oxide' : 'tinymce/skins/ui/oxide-dark',
		content_css: settingsStore.settings.app.colorScheme === 'light' ? 'tinymce/skins/content/default/content.min.css' : 'tinymce/skins/content/dark/content.min.css',
		min_height: 250,
		max_height: 320,
		min_width: 250,
		max_width: 1920,
		selector: 'textarea',
		plugins: 'autolink autoresize fullscreen image insertdatetime link lists media preview table wordcount code searchreplace',
		toolbar: 'undo redo | blocks | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor backcolor removeformat | link image media table insertdatetime searchreplace | preview code fullscreen',
		branding: false,
		menubar: false,
		toolbar_mode: 'sliding',
		insertdatetime_formats: [
			'%Y年%m月%d日',
			'%H点%M分%S秒',
			'%Y-%m-%d',
			'%H:%M:%S',
		],
		content_style: 'video { width: 100%; height: auto; margin: 0; padding: 0; box-shadow: none; display: block; } img {max-width:100%;height:auto;vertical-align:top}',
		file_picker_types: 'media',
		video_template_callback: function (data : any, video_class : any) {
			// 返回自定义的视频HTML
			return '<p style="width: 100%; height:auto; padding:0px; display:flex; justify-content:center; align-items:center;"><video class="' + video_class + '" style="width: 100%; object-fit: cover; margin:0; border:none;display: block;padding: 0px; box-shadow: none; " controls width="100%"  src="' + data.source + '"' +
				' poster="' + data.poster + '">' +
				'<source src="' + data.source + '"' +
				' type="' + data.source_mime + '"></source>' +
				'</video></p>';
		},
		file_picker_callback: function (cb, value, meta) {
			if (meta.filetype == 'media') {
				//创建一个隐藏的type=file的文件选择input
				let input = document.createElement('input');
				input.setAttribute('type', 'file');
				input.onchange = function () {
					let file = this.files[0];//只选取第一个文件。如果要选取全部，后面注意做修改
					uploadvideo(file, (e : any) => {
						cb(e)
					})
				}
				//触发点击
				input.click();
			}
		},
		// https://www.tiny.cloud/docs/tinymce/6/file-image-upload/#images_upload_handler
		images_upload_handler: (blobInfo : any) => new Promise((resolve) => {
			// const img = `data:image/jpeg;base64,${blobInfo.base64()}`
			// resolve(img)
			upload(blobInfo, (e : any) => {
				resolve(e)
			})
		}),
	})
	const content : any = ref()
	const type : any = ref(1)
	const loadingRef : any = ref(null)
	const form : any = ref({})
	const percent : any = ref(false)
	const percentnum : any = ref(0)
	onMounted(() => {
		tinymce.init({})
		getList()
		loadingRef.value.open(1000)
	})
	async function uploadvideo(blobInfo : any, fn : any) {
		console.log(blobInfo, 'blobInfoblobInfo')
		// fullscreenLoading.value = true
		// const formData = new FormData()
		// formData.append('file', blobInfo)
		// // 这里为自己的上传接口调用方法
		// userApi.upload(formData).then((res : any) => {
		// 	console.log(res, 'res')
		// 	fullscreenLoading.value = false
		// 	if (res) {
		// 		fn && fn(baseurl.value + res.url)
		// 	}
		// 	else {
		// 		ElMessage.error('图片上传失败')
		// 		fn && fn('')
		// 	}
		// })
		const token : any = await qiniu_token(blobInfo)
		const fileData : FileData = { type: 'file', data: blobInfo }
		let config = {
			useCdnDomain: true,
			region: 'z2', // 根据实际地区选择
			retryCount: 3, //上传自动重试次数  默认3次
			tokenProvider: () => {
				return Promise.resolve(token)
			},
		};
		const uploadTask = createMultipartUploadV2Task(fileData, config);
		console.log(uploadTask, 'uploadTask 1')

		percent.value = true
		// 设置进度回调函数
		uploadTask.onProgress((progress : any, context : any) => {
			// 处理进度回调
			// console.log(progress, context, progress.percent, 'context123')
			percentnum.value = Math.round((((progress.percent * 100) - 75) * 4 || 0))
			console.log(progress, context, progress.percent, percentnum.value, 'context123')
		});

		// 设置完成回调函数
		uploadTask.onComplete((result : any, context : any) => {
			// 处理完成回调
			console.log(JSON.parse(result), context, '设置完成回调函数')
			percentnum.value = 100
			let newResult = JSON.parse(result)
			// if (!form.value.name) {
			// 	form.value.name = file.name
			// }
			// form.value.file = newResult.key
			fn && fn(baseurl.value + '/' + newResult.key)
			console.log(newResult, 'newResultnewResult')
			// console.log(form.value, 'that.form')
			setTimeout(() => {
				percent.value = false
				ElMessage.success(`资源上传成功`)
				percentnum.value = 0
			}, 500)
		});

		// 设置错误回调函数
		uploadTask.onError((error : any, context : any) => {
			percent.value = 0
			console.log(error, context, '设置错误回调函数')
			percent.value = false
			ElMessageBox.alert('文件上传失败，请联系管理员', '提示', {
				callback: (action : any) => { },
			})

		});

		uploadTask.start()
	}

	// 获取7牛token
	function qiniu_token(file : any) {
		console.log(file)
		return new Promise((resolve : any, reject : any) => {
			userApi.getToken({
				ext: file.name.substring(file.name.lastIndexOf('.') + 1)
			}).then((res : any) => {
				console.log(res, 'resres')
				resolve(res.token)
			}).catch((err : any) => {
				ElMessageBox.alert('七牛token验证失败，请联系管理员', '提示', {
					callback: (action : any) => { },
				})
				reject(err)
			})
		});
	}
	async function upload(blobInfo : any, fn : any) {
		// const loadingInstance = ElLoading.service({
		// 	lock: true,
		// 	text: '上传中...',
		// 	background: 'rgba(0, 0, 0, 0.7)',
		// })
		// fullscreenLoading.value = true
		// const formData = new FormData()
		// formData.append('file', blobInfo.blob())
		// // 这里为自己的上传接口调用方法
		// userApi.upload(formData).then((res : any) => {
		// 	console.log(res, 'res')
		// 	fullscreenLoading.value = false
		// 	if (res) {
		// 		fn && fn(baseurl.value + res.url)

		// 	}
		// 	else {
		// 		ElMessage.error('图片上传失败')
		// 		fn && fn('')
		// 	}
		// })
		const token : any = await qiniu_token(blobInfo.blob())
		const fileData : FileData = { type: 'file', data: blobInfo.blob() }
		let config = {
			useCdnDomain: true,
			region: 'z2', // 根据实际地区选择
			retryCount: 3, //上传自动重试次数  默认3次
			tokenProvider: () => {
				return Promise.resolve(token)
			},
		};
		const uploadTask = createMultipartUploadV2Task(fileData, config);
		console.log(uploadTask, 'uploadTask 1')

		percent.value = true
		// 设置进度回调函数
		uploadTask.onProgress((progress : any, context : any) => {
			// 处理进度回调
			// console.log(progress, context, progress.percent, 'context123')
			percentnum.value = Math.round((((progress.percent * 100) - 75) * 4 || 0))
			console.log(progress, context, progress.percent, percentnum.value, 'context123')
		});

		// 设置完成回调函数
		uploadTask.onComplete((result : any, context : any) => {
			// 处理完成回调
			console.log(JSON.parse(result), context, '设置完成回调函数')
			percentnum.value = 100
			let newResult = JSON.parse(result)
			// if (!form.value.name) {
			// 	form.value.name = file.name
			// }
			// form.value.file = newResult.key
			fn && fn(baseurl.value + '/' + newResult.key)
			console.log(newResult, 'newResultnewResult')
			// console.log(form.value, 'that.form')
			setTimeout(() => {
				percent.value = false
				ElMessage.success(`资源上传成功`)
				percentnum.value = 0
			}, 500)
		});

		// 设置错误回调函数
		uploadTask.onError((error : any, context : any) => {
			percent.value = 0
			console.log(error, context, '设置错误回调函数')
			percent.value = false
			ElMessageBox.alert('文件上传失败，请联系管理员', '提示', {
				callback: (action : any) => { },
			})

		});

		uploadTask.start()

	}

	// 请求列表
	function getList() {
		setupApi.RichText_info({
			id: Number(type.value),
		}).then((res : any) => {
			form.value = {}
			form.value = res
			console.log(form.value, res, 'form.valueform.value')
		})
	}
	// 底部提交按钮
	function onSubmit() {
		console.log(form.value, 'form.valueform.value')
		ElMessageBox.confirm('是否修改当前数据?')
			.then(() => {
				setupApi.RichText_edit({
					id: Number(type.value),
					title: form.value.title,
					content: form.value.content,
				}).then((res : any) => {
					ElMessage({
						message: res.msg,
						type: 'success',
					})
				})
			})
			.catch(() => {
				ElMessage({
					message: '取消修改',
					type: 'success',
				})
			})
	}
	function handleSuccess(res : any) {
		// const handleSuccess1: Uplofunction onCancel() {adProps['onSuccess'] = (res: any) => {
		console.log(res, 'res;;;')
		if (res) {
			// form.value.image = baseurl.value + res.data
			form.value.image = res
		}
		else {
			form.value.image = ""
		}
	}
	/* 切换菜单 */
	function handleClick(tab : TabsPaneContext) {
		type.value = tab.props.name
		getList()
		loadingRef.value.open(1000)
	}
	function closeLoad() {
		fullscreenLoading.value = false
	}
</script>

<template>
	<div class="conference add">
		<page-main style="height: calc(100vh - 240px);">
			<el-tabs v-model="activeName" style="margin-top: -15px;" @tab-click="handleClick">
				<el-tab-pane label="约伴规则" name="1" />
				<el-tab-pane label="隐私协议" name="2" />
			</el-tabs>
			<loading ref="loadingRef" />
			<!-- <div class="flex my-2" v-if="activeName==='6' || activeName==='7' || activeName==='8'">
				<div class="mr-4 my-2">首页封面图：</div>
				<div>
					<ImageUpload v-model:url="form.image" :width="80" :height="80" @onSuccess="handleSuccess" />
				</div>
			</div> -->
			<div class="h-55vh" style="overflow-y: auto;">
				<TinymceEditor v-model="form.content" :init="defaultSetting" />
			</div>
		</page-main>
		<fixed-action-bar>
			<el-button type="primary" size="large" style="padding: 8px 40px;" @click="onSubmit"
				v-if="activeName==='1' && userStore.permissions.includes('yuebanedit')">
				确定
			</el-button>
			<el-button type="primary" size="large" style="padding: 8px 40px;" @click="onSubmit"
				v-if="activeName==='2' && userStore.permissions.includes('yinsiedit')">
				确定
			</el-button>
		</fixed-action-bar>

		<!-- 上传时的加载遮罩层 -->
		<div v-if="fullscreenLoading" class="loading-mask">
			<div class="flex justify-center items-center d-c ">
				<div class=" c-[#409eff]">
					<img class="w-5 h-5" :src="loadicon" alt>
				</div>
				<div class="my-4 c-[#409eff]">上传中...</div>
				<!-- 添加关闭按钮 -->
				<!-- <el-button type="warning" @click="cancelUpload">取消上传</el-button> -->
				<div style="position: fixed; top:60px;right:60px; z-index:1000000;  border-radius: 50%; background-color: rgba(255, 255, 255, 0.8);"
					class="w-16 h-16 flex justify-center items-center font-size-10 cursor-pointer c-[#333]"
					@click="closeLoad">
					<svg-icon name="ep:close" />
				</div>
			</div>
		</div>
		<div v-if="percent" class="fixed demo-progress w-130 bg-[#fff]  top-50% left-50% "
			style="transform: translate(-50%,-50%); border-radius: 8px; box-shadow: 0px 0px 8px 0px #999; z-index:99999;">
			<!-- <div class="w-full text-end pr-4 pt-4 font-size-6 cursor-pointer" @click="closepercent">
				<svg-icon name="ep:close" />
			</div> -->
			<div class="w-full d-c flex justify-center items-center h-40  py-2 h-16" style=" ">
				<el-progress :width="500" striped striped-flow :text-inside="true" :stroke-width="24"
					:percentage="percentnum" status="success" />

				<div>
					<div class="my-4 c-[#67c23a]" v-if="percentnum>0">上传中...</div>
					<div class="my-4 c-[#e67c28]" v-else>正在解析文件流...</div>
				</div>

			</div>

		</div>
	</div>
</template>

<style scoped lang="scss">
	.conference {
		position: relative;

		:deep(.tox-tinymce) {
			height: 52vh !important;
		}
	}

	.demo-progress .el-progress--line {
		margin-bottom: 15px;
		width: 450px;
		height: 30px;
	}

	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2000;
		/* 确保在el-loading之上 */
	}

	.el-loading {
		position: relative;
	}

	.el-loading .el-button {
		position: absolute;
		top: 10px;
		right: 10px;
	}

	.add {
		:deep(.tox-tinymce) {
			width: 375px !important;
			height: 675px !important;
		}
	}
</style>